
package code.codeworld.common.dict.service.impl;

import code.codeworld.common.dict.mapper.DictJPA;
import code.codeworld.common.dict.mapper.DictMapper;
import code.codeworld.common.dict.model.Dict;
import code.codeworld.common.dict.model.vo.DictVo;
import code.codeworld.common.dict.service.DictService;
import code.codeworld.common.system.redis.RedisUtil;
import code.codeworld.common.kits.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static code.codeworld.common.dict.model.constant.DictConstant.DICT_LIST_REDIS_KEY;

/**
 * DictService接口实现类
 *
 * @author freecode
 * @date 2023/03/23 00:20
 **/
@Service
@AllArgsConstructor
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    private DictJPA dictJPA;
    private DictMapper dictMapper;
    private RedisUtil redisUtil;

    @Override
    public Result<List<Dict>> list(DictVo dictVo) {
        List<Dict> list;
        Object object = redisUtil.hmGet(DICT_LIST_REDIS_KEY, dictVo.getCode());
        if (!ObjectUtils.isEmpty(object)) {
            list = (List<Dict>) object;
        } else {
            LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<Dict>();
            queryWrapper.eq(Dict::getCode, dictVo.getCode());
            list = super.list(queryWrapper);
            if (!ObjectUtils.isEmpty(list)) {
                boolean set = redisUtil.hmSet(DICT_LIST_REDIS_KEY, dictVo.getCode(), list, TimeUnit.DAYS.toSeconds(7));
                if (!set) {
                    log.warn("redisUtil.set(DICT_LIST_REDIS_KEY..) " + set);
                }
            }
        }
        return Result.data(list);
    }

    @Override
    public Result<Dict> detail(Dict dict) {
        return Result.data(queryEntity(dict.getId()));
    }

    public Dict queryEntity(Integer id) {
        return dictJPA.getReferenceById(id);
    }

}
